package com.kmxd.ams.app.arrange.command;

import cn.hutool.core.util.ObjectUtil;
import com.kmxd.ams.client.arrange.IBoxSvc;
import com.kmxd.ams.client.arrange.IDocumentSvc;
import com.kmxd.ams.client.arrange.IVolumeSvc;
import com.kmxd.ams.client.arrange.dto.BreakUpDTO;
import com.kmxd.ams.client.arrange.dto.DetachDTO;
import com.kmxd.ams.core.util.ConvertUtil;
import com.kmxd.ams.core.util.IdUtil;
import com.kmxd.ams.infra.arrange.entity.Box;
import com.kmxd.ams.infra.arrange.entity.Document;
import com.kmxd.ams.infra.arrange.entity.Volume;
import com.kmxd.ams.infra.tmpl.dto.ArchTmplBO;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 打散
 *
 * @author nickbi
 */
@Slf4j
@Component
@AllArgsConstructor
public class BreakUpCmd {
  private final IDocumentSvc documentSvc;
  private final IBoxSvc boxSvc;
  private final IVolumeSvc volumeSvc;

  @Transactional(rollbackFor = Exception.class)
  public void breakUp(BreakUpDTO req) {
    if (req.getTableId().contains(ArchTmplBO.VOLUME)) {

      List<Volume> volumes = volumeSvc.selectListByIds(IdUtil.split(req.getVolIds()));
      if (ObjectUtil.isEmpty(volumes)) {
        return;
      }
      volumes.forEach(
          volume -> {
            Document qry = new Document();
            qry.setTableId(req.getDocTableId());
            qry.setVolId(volume.getId());
            List<Document> documents = documentSvc.selectList(qry);
            documents.forEach(
                document -> {
                  document.setVolId(null);
                  document.setArchCode(null);
                  document.setDocSequence(null);
                });
            documentSvc.updateBatchById(documents);
          });
      volumeSvc.remove(ConvertUtil.toBean(req, DetachDTO.class));
    }
    if (req.getTableId().contains(ArchTmplBO.BOX)) {
      List<Box> boxList = boxSvc.selectListByIds(IdUtil.split(req.getBoxIds()));
      if (ObjectUtil.isEmpty(boxList)) {
        return;
      }
      boxList.forEach(
          box -> {
            Document qry = new Document();
            qry.setTableId(req.getDocTableId());
            qry.setBoxId(box.getId());
            List<Document> documents = documentSvc.selectList(qry);
            documents.forEach(
                document -> {
                  document.setBoxId(null);
                  document.setArchCode(null);
                  document.setDocSequence(null);
                });
            documentSvc.updateBatchById(documents);
          });
      boxSvc.remove(ConvertUtil.toBean(req, DetachDTO.class));
    }
  }
}
